package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"time"
)

const (
	ptsURL  = "https://news.pts.org.tw/dailynews"
	setnURL = "https://www.setn.com/"
)

func main() {
	var targetURL string
	var parser func([]byte) string

	if len(os.Args) == 1 {
		targetURL = ptsURL
		parser = parsePTS
	} else if len(os.Args) > 1 {
		switch os.Args[1] {
		default:
			targetURL = ptsURL
			parser = parsePTS
		case "1":
			targetURL = ptsURL
			parser = parsePTS
		case "2":
			targetURL = setnURL
			parser = parseSETN
		}
	}

	result := fetchSite(targetURL, parser)
	fmt.Printf(result)

	// for ms os
	fmt.Scanln()
}

func fetchSite(targetURL string, parse func([]byte) string) string {
	if targetURL == "" {
		fmt.Println("no such option")
		return ""
	}

	req, err := http.NewRequest("GET", targetURL, nil)
	if err != nil {
		fmt.Println("http.NewRequest: err = " + err.Error())
		return ""
	}

	client := &http.Client{Timeout: 3 * time.Second}
	if client == nil {
		fmt.Println("http.Client is nil")
		return ""
	}

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("http.Client.Do: err = " + err.Error())
		return ""
	}
	defer resp.Body.Close()

	pageData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("ioutil.ReadAll: err = " + err.Error())
		return ""
	}

	ret := parse(pageData)
	return ret
}

func parsePTS(data []byte) string {
	titles := ""

	titlePattern := regexp.MustCompile(`title\=\".*?\"`)
	titleList := titlePattern.FindAll(data, -1)

	titleStripPattern := regexp.MustCompile(`(title\=|\")`)
	for _, matchedBt := range titleList {
		titles += fmt.Sprintf("%s\n", titleStripPattern.ReplaceAll(matchedBt, []byte("")))
	}

	return titles
}

func parseSETN(data []byte) string {
	titles := ""
	newsidPattern := regexp.MustCompile(`NewsID.*?\<`)
	newsidList := newsidPattern.FindAll(data, -1)

	attrStripPattern := regexp.MustCompile(`.*?>`)
	part := ""
	for _, matchedBt := range newsidList {
		part = fmt.Sprintf("%s", attrStripPattern.ReplaceAll(matchedBt, []byte("")))
		part := part[:len(part)-1]
		if part != "" {
			titles += part + "\n"
		}
	}

	return titles
}
